﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinHBM.Core.DB;
using WinHBM.Core.module;
using WinHBM.Core.Net.Http;
using WinHBM.Utils;

namespace WinHBM.Core.Task
{
    public class UpdateBabyInfoTask
    {

        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(UpdateBabyInfoTask));
        private static string RequestPrefix, QiNiuPrefix;
        private static string TABLE_BABY = "babyInfo";
        private static Thread thread;


        public static void Start()
        {
            while (!TokenHolder.isLogin)
            {
                Thread.Sleep(1000);
            }
            thread = new Thread(DoTask);
            thread.Name = "UpdateBabyInfoTask";
            thread.IsBackground = true;
            thread.Start();
        }

        public static void Stop()
        {
            if (thread == null || thread.IsAlive == false)
            {
                return;
            }

            thread.Abort();
        }

        

        /**
         *  更新一次本班的宝宝信息表，无论更新成功与否，该只执行一次
         */
        private static void DoTask() {
            Logger.Debug("UpdateBabyInfoTask is running");
            LoginStatus.SYNC_BABY = 1;
            //Thread.Sleep(1000 * 2);
            try
            {
                NameValueCollection appSettings = ConfigurationSettings.AppSettings;
                RequestPrefix = appSettings["apiHost"];
                QiNiuPrefix = appSettings["qiniuHost"];

                // 本班宝宝信息接口调用 
                JObject result = UtilRequest.DoRequest("/api/baby/all-baby", RequestMethod.POST, null);

                if (result.ContainsKey("contents"))
                {

                    JArray babyJArray = (JArray)result["contents"];
                    if (babyJArray.Count <= 0) return;

                    List<Baby> newBabyList = babyJArray.ToObject<List<Baby>>();
                    foreach (Baby baby in newBabyList)
                    {
                        //下载头像

                        string filePath = Application.StartupPath + @"\images\head\"+ UtilMD5.encodeString(baby.avatar) + @".jpg";
                        Logger.Debug("download file " + filePath);
                        DownloadRes.downloadSync(baby.avatar, filePath);
                        //string avatarNativePath = filePath
                        baby.avatar = filePath;
                        //更新数据库
                        DB_SaveBaby(baby);
                    }
                    //过滤换班
                    DB_FilterChangeClass(newBabyList);
                }
                LoginStatus.SYNC_BABY = 2;
            }
            catch (Exception e)
            {
                LoginStatus.SYNC_BABY = 3;
                Logger.Error(e);
            }
            
        }

        private static void DB_FilterChangeClass(List<Baby> babyList)
        {

           

            String classId = babyList.First<Baby>().class_id;
            Dictionary<string, string> BabyClassIdDic  =  UtilDict.make<string, string>("classId", classId );

            List<Dictionary<string,string>> SQLResult =  SQLiteHelper.Instance.find(TABLE_BABY, BabyClassIdDic);

            foreach (Dictionary<string, string> dic in SQLResult) {
                bool isChange =   IsBabyChangeClass(dic["babyId"], babyList);

                if (isChange) {
                    Dictionary<string, string> dic_condition = UtilDict.make<string, string>("babyId", dic["babyId"]);
                    dic["classId"] = "0";
                    SQLiteHelper.Instance.update(TABLE_BABY,dic, dic_condition);
                }
            }
        }

        private static bool IsBabyChangeClass(String babyId, List<Baby> babyList) {
            bool isChange = true;
            foreach (Baby baby in babyList) {
                if (babyId.Equals(baby.id)) {
                    isChange = false;
                    break;
                }
            }
            return isChange;
        }


        private static void DB_SaveBaby(Baby baby)
        {
            Dictionary<string, string> dic_babyId = UtilDict.make<string, string>("babyId", baby.id);
            Dictionary<string, string> dic_baby_all = UtilDict.make<string, string>("babyId", baby.id, "classId", baby.class_id, "name", baby.name, "avatar", baby.avatar, "red", baby.red);
            List<Dictionary<string,string>> list =  SQLiteHelper.Instance.find(TABLE_BABY, dic_babyId);

            if (list.Count > 0)
            {
                SQLiteHelper.Instance.update(TABLE_BABY, dic_baby_all, dic_babyId);
            }
            else
            {
                SQLiteHelper.Instance.insert(TABLE_BABY, dic_baby_all);
            }

        }

        /*private static JObject DoRequest(string url, RequestMethod method, JObject body)
        {
            string result;
            try
            {
              
                if (!url.StartsWith("http") && !url.StartsWith("https"))
                {
                    url = RequestPrefix + url;
                }

                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                HttpWebRequest webReq = HttpWebRequest.Create(url) as HttpWebRequest;
                webReq.Method = method.ToString();
                webReq.ContentType = "application/json";
                if (!String.IsNullOrEmpty(TokenHolder.Token))
                {
                    webReq.Headers["Authorization"] = "Bearer " + TokenHolder.Token;
                }

                if (method.Equals(RequestMethod.POST) && body != null)
                {
                    byte[] btBodys = Encoding.UTF8.GetBytes(body.ToString());
                    webReq.ContentLength = btBodys.Length;
                    Stream bodyStream = webReq.GetRequestStream();
                    bodyStream.Write(btBodys, 0, btBodys.Length);
                    bodyStream.Close();
                }


                HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
                StreamReader steamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
                result = steamReader.ReadToEnd();

                steamReader.Close();
                webReq.Abort();
                webResponse.Close();
            }
            catch (Exception e)
            {
                Dictionary<String,Object> ExceptionDic = new Dictionary<String, Object>();
                ExceptionDic.Add("errcode", -1);
                ExceptionDic.Add("message",e.Message);
                result = JsonConvert.SerializeObject(ExceptionDic);
            }

            return JObject.Parse(result);
        }


        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }*/



    }

}
